package com.marketlive.app.b2c;

/*
 (C) Copyright MarketLive. 2006. All rights reserved.
 MarketLive is a trademark of MarketLive, Inc.
 Warning: This computer program is protected by copyright law and international treaties.
 Unauthorized reproduction or distribution of this program, or any portion of it, may result
 in severe civil and criminal penalties, and will be prosecuted to the maximum extent
 possible under the law.
 */


import com.marketlive.app.b2c.nav.ILinkGenerator;
import com.marketlive.app.b2c.tiles.SpringDelegatingDefinitionFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.marketlive.biz.session.context.ICommerceSession;
import org.marketlive.entity.account.IContact;
import org.marketlive.entity.account.IContactHome;
import org.marketlive.entity.account.ICustomer;
import org.marketlive.entity.account.IHintHome;
import org.marketlive.system.config.IConfigurationManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * File Templates.
 */
public class WebUtil {

    /**
     * Logger.
     */
    private static Log log = LogFactory.getLog(WebUtil.class);

    /**
     * Category ID for site root.
     */
    private static final String SITE_ROOT = "1";

    /** Path to the admin application. Requests under this prefix bypass CommerceSession. */
    public static final String ADMIN_PREFIX = "/admin";

    /**
     * Get Spring's WebApplicationContext from the session.
     *
     * @param request request within the servlet context.
     * @return wac the web application context.
     */
    public static final WebApplicationContext getWebApplicationContext(HttpServletRequest request) {
        final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(request
                .getSession().getServletContext());
        if (wc == null) {
            throw new RuntimeException("WebApplicationContext not found");
        }
        return wc;
    }

    


    /**
     * Retunrs the HintHome from the servlet context.
     *
     * @param request the http request object
     * @return home the HintHome associated with the session
     */
    public static final IHintHome getHintHome(HttpServletRequest request) {
        final IHintHome home = (IHintHome) getWebApplicationContext(request).getBean("hintHome");
        return home;
    }

   

    /**
     * Replaces ${NavState} token in forward paths with NavState encoded into query parameters.
     *
     * @param request the http request object
     * @param mapping the action mapping object
     * @param forward the forward action to find
     * @return the ActionForward action
     */
    public static final ActionForward findForward(HttpServletRequest request, ActionMapping mapping, String forward) {

        ActionForward actionForward = mapping.findForward(forward);
        return findForward(request, actionForward);
    }

    /**
     * Replaces ${NavState} token in forward paths with NavState encoded into query parameters.
     *
     * @param request the http request object
     * @param actionForward the forward object to use
     *
     * @return  ActionForward
     */
    public static final ActionForward findForward(HttpServletRequest request, ActionForward actionForward) {
        return actionForward;
    }


    /**
     * Returns the commerce session. The CommerceSessionFilter should be configured to guarantee that a commerce session
     * is always associated with a request.
     *
     * @param request the http request object
     * @return the commerceSession associated with this session.
     */
    public static final ICommerceSession getCommerceSession(HttpServletRequest request) {
        final ICommerceSession session = (ICommerceSession) request.getSession().getAttribute(
                ICommerceSession.COMMERCE_SESSION);
        if (session == null) {
            throw new RuntimeException(
                    "ICommerceSession not found in request. Make sure CommerceSessionFilter is correctly configured.");
        }
        return session;
    }

    /**
     * Returns a List of hint questions.
     *
     *
     * @param request the http request object
     * @return a List of hint questions
     */
    public static List getHintQuestions(HttpServletRequest request) {
        WebApplicationContext wc = getWebApplicationContext(request);
        IHintHome hintHome = (IHintHome) wc.getBean("hintHome");
        return new ArrayList(hintHome.findAll());
    }

    /**
     * Return a list of 10 year numbers.
     *
     * @param locale Locale to use
     * @return A list of 10 year numbers.
     */
    public static List getYearList(Locale locale) {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault(), locale);
        calendar.getTime();
        int year = calendar.get(Calendar.YEAR);
        List yearList = new ArrayList();
        for (int i = 0; i < 10; i++) {
            yearList.add(new Integer(year));
            year++;
        }
        return yearList;
    }

    /**
     * Return the list of months based on user's Locale.
     *
     * @param locale Locale to use
     * @return List Month names based on Locale.
     */
    public static List getMonthList(Locale locale) {
        DateFormatSymbols dfs = new DateFormatSymbols(locale);
        String[] months = dfs.getMonths();

        ArrayList monthList = new ArrayList();
        for (int i = 0; i < 12; i++) {
            monthList.add(months[i]);
        }
        return monthList;
    }

    /**
     * Returns the ConfigurationtManager from the servlet context.
     *
     * @param request the http request object
     * @return IConfiguration Manager.
     */
    public static final IConfigurationManager getConfigurationManager(HttpServletRequest request) {
        return (IConfigurationManager) getWebApplicationContext(request).getBean("configurationManager");
    }

    

   

    /**
     * Retrieve a string from Struts configuration message resource using current locale.
     *
     * @param request the http request object
     * @param messageKey message resource key
     * @return the message for the passed messageKey
     */
    public static String getMessage(HttpServletRequest request, String messageKey) {

        MessageResources mr = ((MessageResources) request.getAttribute(Globals.MESSAGES_KEY));

        Locale locale = WebUtil.getCommerceSession(request).getLocale();

        return mr.getMessage(locale, messageKey);
    }

    /**
     * Retrieve the MessageResources wrapper from the request.
     *
     * @param request the http request object
     * @return the message resource managed by Struts
     */
    public static MessageResources getMessageResources(HttpServletRequest request) {
        return ((MessageResources) request.getAttribute(Globals.MESSAGES_KEY));
    }
    
    /**
     * Returns the Link Generator bean from the application context.
     *
     * @param request the http request object
     * @return the ILinkGenerator needed to build links
     */
    public static ILinkGenerator getLinkGenerator(HttpServletRequest request) {

        WebApplicationContext webContext = SpringDelegatingDefinitionFactory.getRequiredWebApplicationContext(request
                .getSession().getServletContext());

        return (ILinkGenerator) webContext.getBean(ILinkGenerator.LINK_GENERATOR_BEAN);
    }
    
    public static boolean isAdminApplicationRequest(HttpServletRequest httpRequest){
        return false;
    }
}
